<?php

class Adb_Table extends Adb
{

  const OPTION_INNODB = 1;

  const CONSTRAINT_KEY = 'key';

  const CONSTRAINT_UNIQUE = 'unique';

  protected static $instances = array();

  protected $options = array();

  /**
   *
   * @return Adb_Table
   */
  public static function getInstance($table, $profile = 'default')
  {
    if (empty(self::$instances[$table])) {
      self::$instances[$table] = new Adb_Table($table, $profile);
    }

    return self::$instances[$table];
  }

  protected function __construct($name, $profile = 'default')
  {
    parent::__construct($name, $profile);
  }

  public function getFields()
  {
    return $this->manager()->listTableFields($this->getName());
  }

  public function getField($name)
  {
    $field = new Adb_Field($this, $name);
    return $field;
  }

  public function getPrimaryKey()
  {
    return $this->getName() . '_id';
  }

  public function exists()
  {
    $tables = $this->manager()->listTables();
    return in_array($this->getName(), $tables);
  }

  public function setOption($option, $value = null)
  {
    switch ($option) {
      case self::OPTION_INNODB:
        $this->options['type'] = 'innodb';
        break;

      default :
        $this->options[$option] = $value;
    }
  }

  public function create()
  {
    $pk = $this->getPrimaryKey();

    $fields = array(
      $pk => array (
        'type' => 'integer',
        'length' => 4,
        'unsigned' => 1,
        'notnull' => 1,
        'autoincrement' => 1
      )
    );

    $options = $this->options;
    $options['charset'] = 'utf8';
    $options['collate'] = 'utf8_unicode_ci';

    $this->manager()->createTable($this->getName(), $fields, $options);

    $definition = array (
      'primary' => true,
      'fields' => array (
        $pk => array()
      )
    );

    $this->manager()->createConstraint($this->getName(), 'PRIMARY', $definition);
  }

  public function rename($name)
  {
    $this->manager()->alterTable($this->getName(), array('name' => $name), false);
    $this->name = $name;
  }

  public function remove()
  {
    $this->manager()->dropTable($this->getName());
  }

  /**
   *
   * @param string $type key, unique
   */
  public function createConstraint($name, $type, $fields = null)
  {
    $const = $this->manager()->listTableConstraints($this->getName());

    if (in_array($name, $const)) {
      $this->manager()->dropConstraint($this->getName(), $name);
    }

    if (empty($fields)) {
      $fields = $name;
    }

    $fields = (array) $fields;

    $definition = array(
      $type => 1,
      'fields' => array_flip($fields)
    );

    $result = $this->manager()->createConstraint($this->getName(), $name, $definition);

    MDB2_Database::validate($result);
  }

}
